package com.tuling.mybaitis_spring;

import com.tuling.mybaitis_spring.proxy.MybaitisProxyFactoryBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.util.Set;

public class MybatisClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {


	public MybatisClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
		super(registry);
	}

	@Override
	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
		//修改扫描出来的beanDefiniton
		for (BeanDefinitionHolder beanDefinitionHolder:beanDefinitionHolders){
			BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();
			//使用构造注入
			beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName());
			beanDefinition.setBeanClassName(MybaitisProxyFactoryBean.class.getName());
		}
		return beanDefinitionHolders;
	}

	/**
	 * 扫描只是接口的
	 * @param metadataReader the ASM ClassReader for the class
	 * @return
	 * @throws IOException
	 */
	@Override
	protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
		return metadataReader.getClassMetadata().isInterface();
	}

	@Override
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return true;
	}

}
